<template>
  <div class="vuln-environment-list">
    <!-- 新增：搜索输入框 -->
    <div class="search-form">
      <el-form-item label="关键字搜索">
        <el-input
          style="max-width: 320px;"
          v-model="keyword"
          clearable
          placeholder="请输入关键字进行搜索"
          @clear="handleKeywordClear"
          @input="fetchEnvironmentList"
        />
      </el-form-item>
    </div>
    <!-- 漏洞列表 -->
    <base-table
      :data="environmentList"
      :loading="loading"
      :total="total"
      v-model:page="currentPage"
      v-model:limit="pageSize"
      @pagination="handleCurrentChange"
      @selection-change="handleSizeChange"
    >
      <el-table-column prop="ID" label="ID" width="80"/>
      <el-table-column label="环境名称">
        <template #default="{ row }">           
           <el-tooltip :content="row.name" placement="top" :show-after="1000">
            <div class="ellipsis-3lines">{{ row.name }}</div>
           </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="漏洞名称" width="300">
        <template #default="{ row }">
          <div class="ellipsis-3lines">{{ row.comment || '--' }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="env_status" label="环境状态" width="120">
        <template #default="{ row }">
          <div class="status-badge" :class="row.env_status ? 'status-running' : 'status-stopped'">
            <span class="status-dot"></span>
            {{ row.env_status ? '已启动' : '未启动' }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="eventStatus" label="启动漏洞验证" width="280">
        <template #default="{ row }">
          <el-select class="node-select" v-model="row.selectedNode" placeholder="请选择节点" clearable>
            <el-option v-for="item in row.nodes" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
          <el-button type="primary" link icon="Open" @click="handleStart(row)" :disabled="!row.selectedNode">
            启动漏洞验证
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template #default="{ row }">
          <el-button type="primary" link icon="Open" @click="handleEdit(row, 'start')" :disabled="row.env_status">
            启动
          </el-button>
          <el-button type="primary" link icon="Close" @click="handleEdit(row, 'stop')" :disabled="!row.env_status">
            关闭
          </el-button>
          <el-button type="primary" link icon="InfoFilled" @click="handleInfo(row)">
            查看详情
          </el-button>
        </template>
      </el-table-column>
    </base-table>
    <el-dialog v-model="verificationEnvDialog" title="漏洞验证" width="500">
      <el-form :model="verificationForm" :rules="verificationRules" ref="verificationFormRef" label-width="100px" style="padding-top: 20px;">
        <el-form-item label="环境名称" prop="envName">
          <el-input v-model="verificationForm.envName" placeholder="请输入环境名称"></el-input>
        </el-form-item>
        <el-form-item label="IP地址" prop="ip">
          <el-input v-model="verificationForm.ip" placeholder="请输入IP地址" disabled></el-input>
        </el-form-item>
        <el-form-item label="漏洞名称" prop="vulnName">
          <el-input v-model="verificationForm.vulnName" placeholder="请输入漏洞名称" disabled></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer-vuln">
          <el-button @click="verificationEnvDialog = false">取消</el-button>
          <el-button type="primary" @click="submitVerificationForm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  getVulnEnvironmentList,
  OperateVulnEnvironment,
  startVuln,
  getDescFunc
} from "@/api/topo";
import BaseTable from "@/components/BaseTable/index.vue";
import { useRouter } from 'vue-router';
import { ElMessageBox, ElMessage } from 'element-plus';
import { ref, onMounted, onUnmounted, reactive } from 'vue';
import { useCommonStore } from "@/stores/common";
const { setTaskId, setQemuId, setVulnTitle, setVulnType, setTaskName, setEnvId, setEnvName, setEnvComment } = useCommonStore();

const verificationEnvDialog = ref(false);
const router = useRouter();
// 数据和加载状态
const loading = ref(false);
const isFirstLoad = ref(true);
const environmentList = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const statusFilter = ref("");
const verificationFormRef = ref();
const verificationForm = reactive({
  id: '',
  ip: '',
  vulnName: '',
  envName: '',
  // qemu_id: '',
  env_type: 0,
  node_env_id: ''
});
const timerId = ref(null);
const keyword = ref("");

// 验证规则
const verificationRules = {
  envName: [
    { required: true, message: '请输入环境名称', trigger: 'blur' },
  ]
};

// 获取环境列表
const fetchEnvironmentList = async () => {
  const shouldShowLoading = isFirstLoad.value;
  if (shouldShowLoading) {
    loading.value = true;
  }
  try {
    const params = {
      page_index: currentPage.value,
      page_size: pageSize.value,

    };

    if (statusFilter.value) {
      params.status = statusFilter.value;
    }
    // 新增：关键字搜索
    if (keyword.value) {
      params.keyword = keyword.value;
    }

    const { data } = await getVulnEnvironmentList(params);
    environmentList.value = data.list.map(item => {
      return {
        ...item,
        selectedNode: '', // 为每行添加独立的选中节点
        nodes: item.nodes || []
      }
    });
    total.value = data.total;
  } catch (error) {
    console.error("获取漏洞验证环境列表失败", error);
    ElMessage.error("获取漏洞验证环境列表失败");
  } finally {
    if (shouldShowLoading) {
      loading.value = false;
      isFirstLoad.value = false;
    }
  }
};

// 新增：清空搜索关键字时刷新列表
const handleKeywordClear = () => {
  fetchEnvironmentList();
};

// 提交验证表单
const submitVerificationForm = async () => {
  if (!verificationFormRef.value) return;
  await verificationFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      const res = await startVuln({
        name: verificationForm.envName,
        ip: verificationForm.ip,
        exploit: verificationForm.vulnName,
        id: verificationForm.id,
        // qemu_id: verificationForm.qemu_id,
        env_type: verificationForm.env_type,
        node_env_id: verificationForm.node_env_id
      });      
      if(res.code === 200){
        ElMessage.success('验证任务创建成功');
        setTaskId(res.data.task_id || verificationForm.id);
        setQemuId(verificationForm.node_env_id);  
        setVulnTitle(verificationForm.vulnName);
        setVulnType(verificationForm.env_type)
        setTaskName(verificationForm.envName)
        setTimeout(() => {
          router.push({
            name: 'ProcessMonitor',
            query: {
              id: res.data.task_id || verificationForm.id,
              // qemu_id: verificationForm.qemu_id
              vuln_title: verificationForm.vulnName,
              env_type: verificationForm.env_type,
              node_env_id: verificationForm.node_env_id,
            }
          })
        }, 1000);
      }
    } else {
      console.log('验证失败', fields);
    }
  });
};

// 启动node验证
const handleStart = (row) => {
  if (!row.selectedNode) {
    ElMessage.warning('请先选择节点');
    return;
  }
  getDescFunc(row.ID, row.selectedNode).then(res => {
    if(res.code === 200){
      const resp = row.nodes.find(item => item.id === row.selectedNode);
      console.log('resp', resp)

      verificationForm.id = row.ID;
      verificationForm.envName = row.name;
      verificationForm.vulnName = row.comment;
      verificationForm.env_type = resp.env_type;
      verificationForm.node_env_id = resp.node_env_id;
      verificationForm.ip = res.data.instancePorts[0]?.ipV4?.split('/')[0];
      // verificationForm.qemu_id = res.data.qemuID;
      verificationEnvDialog.value = true;
      console.log('verificationForm', verificationForm)
    }
  })
}

// 开启 关闭
const handleEdit = (row, type) => {
  // 二次确认提醒
  ElMessageBox.confirm(
    `确定要${type === 'start' ? '启动' : '停止'}该验证环境吗？`,
    '操作确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
.then(() => {
  // 用户确认操作后继续执行
  OperateVulnEnvironment({
    id: row.ID,
    operation: type
  }).then(res => {
    if (res.code === 200) {
      ElMessage.success("操作成功");
      fetchEnvironmentList();
    } else {
        ElMessage.error(res.message);
      }
    });
  });
}

// 处理分页变化
const handleSizeChange = (val) => {
  pageSize.value = val.limit;
  currentPage.value = val.page;
  fetchEnvironmentList();
};

const handleCurrentChange = (val) => {
  currentPage.value = val.page;
  pageSize.value = val.limit;
  fetchEnvironmentList();
};

// 组件挂载时加载数据
onMounted(() => {
  fetchEnvironmentList();
  timerId.value = setInterval(fetchEnvironmentList, 10000);
});

onUnmounted(() => {
  if (timerId.value) {
    clearInterval(timerId.value);
    timerId.value = null;
  }
});
// 跳转详情
const handleInfo = (data) => {
  setEnvId(data.ID)
  setEnvName(data.name)
  setEnvComment(data.comment)
  router.push({
    name: 'ScenesManage',
    query: {
      id: data.ID,
      name: data.name,
      comment: data.comment,
    },
  });
}
</script>

<style lang="scss" scoped>
.vuln-environment-list {
  padding: 16px;

  .header-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h1 {
      font-size: 20px;
      font-weight: bold;
      margin: 0;
    }
  }

  .node-select {
    width: 120px;
    margin-right: 10px;
  }

  .status-badge {
    display: inline-flex;
    align-items: center;
    border-radius: 10px;
    font-size: 13px;
    min-width: 90px;
    justify-content: center;
  }
    .status-running {
      background-color: rgba(19, 206, 102, 0.15);
      color: #13ce66;

      .status-dot {
        background-color: #13ce66;
        box-shadow: 0 0 0 2px rgba(19, 206, 102, 0.2);
      }
    }

    .status-stopped {
      background-color: rgba(245, 108, 108, 0.15);
      color: #f56c6c;

      .status-dot {
        background-color: #f56c6c;
        box-shadow: 0 0 0 2px rgba(245, 108, 108, 0.2);
      }
    }
  .status-dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    margin-right: 6px;
    display: inline-block;
  }

.ellipsis-3lines {
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    word-break: break-all;
    line-height: 1.5;
    max-height: 4.5em;

    

    &.status-running {
      background-color: rgba(19, 206, 102, 0.15);
      color: #13ce66;

      .status-dot {
        background-color: #13ce66;
        box-shadow: 0 0 0 2px rgba(19, 206, 102, 0.2);
      }
    }

    &.status-stopped {
      background-color: rgba(245, 108, 108, 0.15);
      color: #f56c6c;

      .status-dot {
        background-color: #f56c6c;
        box-shadow: 0 0 0 2px rgba(245, 108, 108, 0.2);
      }
    }
  }

  :deep(.el-dialog__body) {
    padding-top: 10px;
  }

  .dialog-footer-vuln {
    display: flex;
    justify-content: flex-end;
  }

  :deep(.el-table) {
    --el-table-border-color: var(--el-border-color-lighter);
    --el-table-header-bg-color: var(--el-fill-color-light);
  }

  .search-form {
    margin-bottom: 20px;
    background: var(--card-bg);
    padding: 20px;
    width: 100%;
  }
}

html.dark {
  .vuln-environment-list {
    .status-badge {
      &.status-running {
        background-color: rgba(19, 206, 102, 0.15);
        color: #13ce66;
      }

      &.status-stopped {
        background-color: rgba(245, 108, 108, 0.15);
        color: #f56c6c;
      }
    }
  }
}
</style>
